package cn.wei.example.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wei.example.common.model.User;
import cn.wei.example.common.service.UserService;
import cn.wei.youvierpc.model.RpcRequest;
import cn.wei.youvierpc.model.RpcResponse;
import cn.wei.youvierpc.serializer.JdkSerializer;
import cn.wei.youvierpc.serializer.Serializer;

import java.io.IOException;

public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        Serializer serializer = new JdkSerializer();
        RpcRequest rpcRequest = RpcRequest.builder().methodName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();
        try {
            byte[] serialize = serializer.serialize(rpcRequest);
            byte[] resultBytes;
            try (HttpResponse response = HttpRequest.post("http://localhost:8085")
                    .body(serialize)
                    .execute()) {
                resultBytes = response.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(resultBytes, RpcResponse.class);
            return (User) rpcResponse.getData();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
